#include <vector>
#include <queue>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> levelOrderSeq;
        queue<TreeNode*> levelOrderQueue;

        if (root)
            levelOrderQueue.push(root);

        while (!levelOrderQueue.empty())
        {
            int OldSize = levelOrderQueue.size();
            vector<int> currentLayerNodes;

            while (OldSize--)
            {
                TreeNode* node = levelOrderQueue.front();
                levelOrderQueue.pop();

                if (node->left)
                    levelOrderQueue.push(node->left);
                if (node->right)
                    levelOrderQueue.push(node->right);

                currentLayerNodes.push_back(node->val);
            }

            levelOrderSeq.push_back(currentLayerNodes);
        }

        reverse(levelOrderSeq.begin(), levelOrderSeq.end());
        return levelOrderSeq;
    }
};